package com.jdog.chat.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.LinkedBlockingQueue;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.continuation.Continuation;
import org.eclipse.jetty.continuation.ContinuationSupport;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jdog.chat.contrainer.ClientUtil;
import com.jdog.chat.entity.Client;

@Controller
@RequestMapping("/room")
public class RoomController {
	
	@RequestMapping("/login")
	public String login(String username, Model model) {
		String loginMessage = "您好:" + username;
		Client client = null;
		if(ClientUtil.getInstance().getClientByUsername(username) != null) {
			client = ClientUtil.getInstance().getClientByUsername(username);
		} else {
			client = new Client();
			client.setUsername(username);
			client.setQueue(new LinkedBlockingQueue<String>());
			ClientUtil.getInstance().add(client);
			
			CopyOnWriteArrayList<Client> list = ClientUtil.getInstance().getClientsList();
			for(Client lc : list) {
				synchronized(lc) {
					lc.getQueue().add("refreshList");
				}
				
				if(lc.getContinuation() != null) {
					lc.getContinuation().resume();
					lc.setContinuation(null);
				}
			}
		}
		model.addAttribute("username", username);
		model.addAttribute("loginMessage", loginMessage);
		return "main";
	}
	
	@RequestMapping("/getMsg")
	public void getMsg(HttpServletRequest request, HttpServletResponse response, String username) throws IOException {
		PrintWriter out = response.getWriter();
		Client client = ClientUtil.getInstance().getClientByUsername(username);
		synchronized(client) {
			if(client.getQueue().size() > 0) {
				String msg = "";
				while(client.getQueue().size() > 0) {
					if(client.getQueue().size() == 1) {
						msg += client.getQueue().poll();
					} else {
						msg += client.getQueue().poll() + "|";
					}
					
				}
				out.print(msg);
				out.flush();
			} else {
				Continuation continuation = ContinuationSupport.getContinuation(request);
				if(continuation.isInitial()) {
					continuation.setTimeout(60000);
					continuation.suspend();
					client.setContinuation(continuation);
				} else {
					out.print("nomessages");
					out.flush();
				}
			}
		}
	}
	
	@RequestMapping("refreshList")
	@ResponseBody
	public String refreshList() {
		CopyOnWriteArrayList<Client> list = ClientUtil.getInstance().getClientsList();
		String result = "";
		for(Client c : list) {
			result += c.getUsername() + "|";
		}
		return result;
	}
}
